import finalshu.FinalShu;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 过滤器，判断你等录与否
 */
//@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("filter");
        HttpServletRequest req = (HttpServletRequest)servletRequest;
        HttpServletResponse resp = (HttpServletResponse)servletResponse;
        String reqURI = req.getRequestURI();
        if (null == reqURI || reqURI.equals(req.getContextPath())
                ||reqURI.equals(req.getContextPath()+"/")
                ||reqURI.equals(req.getContextPath()+"/index.jsp")
                ||reqURI.equals(req.getContextPath()+"/loginSrevlet")
                ||reqURI.toLowerCase().endsWith(".css")
                ||reqURI.toLowerCase().endsWith(".js")
                ||reqURI.toLowerCase().endsWith(".png")
                ||reqURI.toLowerCase().endsWith(".jpg")
                ||reqURI.toLowerCase().endsWith(".webp")
                ||reqURI.toLowerCase().endsWith(".html")
        )
        {
            filterChain.doFilter(servletRequest,servletResponse);
        }
        else {
            HttpSession session = req.getSession();
            Object attribute = session.getAttribute(FinalShu.FINAL_ID);
            if (null==attribute){
                req.setAttribute(FinalShu.FINAL_INFO,"抱歉，没有登录！");
                req.getRequestDispatcher("/index.jsp").forward(req,resp);
            }
            filterChain.doFilter(servletRequest,servletResponse);
        }

    }

    @Override
    public void destroy() {
        System.out.println("结束");
    }
}
